package com.zy.config;

import cn.hutool.core.util.ObjectUtil;
import com.zy.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign拦截器
 *     token传递，解决服务之间调用没有token的问题
 * 请求传递方式：
 *     1.浏览器 -> A服务 -> B服务 (存在token)
 *     2.定时器等 -> A服务 -> B服务 (不存在token，给一个固定token)
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取当前请求的上下文对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //判断请求上下文是否为空
        if (ObjectUtil.isNotNull(requestAttributes)) {
            //获取请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            //判断请求是否为空
            if (ObjectUtil.isNotNull(request)) {
                //获取当前请求的Authorization值，传递到下一个请求的请求头中
                //格式 Authorization="bearer " + token(UUID)
                String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
                requestTemplate.header(AuthConstants.AUTHORIZATION, authorization);
                return;
            }
        }
        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "bd33afed-69b5-4e8c-bf2c-5a23198a015e");
    }
}
